package cn.edu.imau.zy.dfs.controller;

import cn.edu.imau.zy.common.core.domain.R;
import cn.edu.imau.zy.common.utils.StringUtils;
import cn.edu.imau.zy.common.utils.file.FileUploadUtils;
import cn.edu.imau.zy.common.utils.file.FileUtils;
import cn.edu.imau.zy.dfs.config.DfsConfig;
import cn.edu.imau.zy.dfs.service.IDfsFileService;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用请求处理
 * 
 *
 */
@Slf4j
@RestController
public class FileController
{
    @Autowired
    private DfsConfig dfsConfig;

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("download")
    public void download(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = dfsConfig.getPath() + fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition","attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception
    {
        if(file == null){
            throw new Exception("请选择上传文件");
        }
        try
        {
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = IdUtil.getSnowflake(2,2).nextIdStr()+extName;
            // 上传文件路径
            String filePath = dfsConfig.getPath() + fileName;
            File path = new File(dfsConfig.getPath());
            if(!path.exists()){
                path.mkdirs();
            }
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(filePath));
            return R.ok().put("fileName", fileName);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 富文本上传请求
     */
    @PostMapping("tinyUpload")
    public R tinyUpload(@RequestParam("file") MultipartFile file) throws Exception
    {
        if(file == null){
            throw new Exception("请选择上传文件");
        }
        try
        {
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = IdUtil.getSnowflake(2,2).nextIdStr()+extName;
            // 上传文件路径
            String filePath = dfsConfig.getPath() + fileName;
            File path = new File(dfsConfig.getPath());
            if(!path.exists()){
                path.mkdirs();
            }
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(filePath));
            return R.ok().put("fileName", dfsConfig.getDomain()+ fileName);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 图片浏览
     */
    @RequestMapping("/img")
    public void img(@RequestParam(value = "fileName") String fileName, HttpServletResponse response) {

        // 文件路径
        String filePath = dfsConfig.getPath() + fileName;
        String extName = fileName.substring(fileName.lastIndexOf("."));
        Map<String,Object> type = new HashMap<>();
        type.put(".jpg","image/jpeg");
        type.put(".jpeg","image/jpeg");
        type.put(".jpe","image/jpeg");
        type.put(".gif","image/gif");
        type.put(".png","image/png");
        type.put(".bmp","image/bmp");

        if(type.containsKey(extName.toLowerCase())){
            FileInputStream fis = null;

            try {
                fis = new FileInputStream(filePath);
                response.setHeader("Content-Type",type.get(extName.toLowerCase()).toString());
                OutputStream out = response.getOutputStream();

                FileCopyUtils.copy(fis , out);

                out.flush();

                out.close();
            } catch ( Exception e ){
                log.error(e.getMessage());
            } finally {
                if (fis != null ) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
        }

    }
}